﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Navigation;
using Coding4Fun.Toolkit.Controls;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Reactive;
using Microsoft.Phone.Shell;
using _300Report.domain;
using _300Report.Global;
using _300Report.Pages;

namespace _300Report.pages
{
    public partial class MainPage : PhoneApplicationPage
    {
        // 构造函数
        public MainPage()
        {
            InitializeComponent();
        
            // 用于本地化 ApplicationBar 的示例代码
            //BuildLocalizedApplicationBar();
        }

        #region Pivot 4 战绩查询


        private RoleInfo _roleInfo;
        public static int MaxPageNum = 0;
        #region  初始化

        /// <summary>
        /// 初始化页面四
        /// </summary>
        private void InitForth()
        {
            //this.RoleScrollViewer.Visibility = Visibility.Collapsed;
        }

        #endregion



        #region 输入框提示

        private void HeroReportTextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            //控制提示内容,输入框得到焦点
            this.HeroTip.Visibility = Visibility.Collapsed;
        }

        private void HeroReportTextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            //控制提示内容,输入框得到焦点
            if (string.IsNullOrWhiteSpace(this.HeroReportTextBox.Text))
            {
                this.HeroTip.Visibility = Visibility.Visible;
            }
            else
            {
                this.HeroTip.Visibility = Visibility.Collapsed;
            }
        }

        #endregion


        #region 角色战报搜索RoleInfo

        /// <summary>
        /// http://300report.jumpw.com/api/getrole?name=张三
        /// 
        /// http://bbs.300hero.net/300z.php?name=gokno
        /// 
        /// 40/9972/812/1639/3904/,伊卡洛斯,黑岩射手,术士娃,我受罗,佐罗,十六夜咲夜,御坂美琴/2014-10-08 23:49:29
        ///等级/节操/胜场/总场/战斗力
        ///         /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Search_Click(object sender, RoutedEventArgs e)
        {
            ToastPrompt prompt = new ToastPrompt();
            prompt.MillisecondsUntilHidden = 1000;
            prompt.MaxHeight = 78;
            if (string.IsNullOrWhiteSpace(this.HeroReportTextBox.Text))
            {

                prompt.Message = "请输入搜索内容 o(︶︿︶)o";
                prompt.Show();
                return;
            }

            if (!Config.CheckNetworkState())
            {
                Config.NetWorkUnaviliableToast();
                return;
            }
            //搜索
            GlobalIndicator.Instance.IsBusy = true;


            Config.HttpGetStringResult(RequestUrl.GetRole(Str2UTF8(this.HeroReportTextBox.Text)))
            .Select(roleString => Config.PareseHeroReport<RoleInfo>(roleString)).ObserveOnDispatcher().
            Do(ex => GlobalIndicator.Instance.IsBusy = false).Subscribe(
            ParseRoleInfo,
            ex => this.Dispatcher.BeginInvoke(() =>
            {
                GlobalIndicator.Instance.IsBusy = false;
                Config.Toast("网络错误,稍等一会儿.....", 800);
            })
            );
        }

        /// <summary>
        /// 角色信息后期处理
        /// </summary>
        /// <param name="role"></param>
        private void ParseRoleInfo(RoleInfo role)
        {
            if (role.Result == "OK")
            {
                _roleInfo = role;
                MaxPageNum = role.Role.MatchCount / 10 + 1;
                //添加至缓存
                var v = Config.GetSearchReportHistory();
                if (v == null)
                {
                    Config.SetIsolatedStorageSettings(SearchReportHistoryPage.SearcHistoryKey,
                        new SortedSet<string> { role.Role.RoleName });
                }
                else
                {
                    v.Add(role.Role.RoleName);
                    Config.SetIsolatedStorageSettings(SearchReportHistoryPage.SearcHistoryKey,
                        v);
                }

                //Config.Toast("共有" + MaxPageNum+"页数据;",800);
                GetRoleEfficient(role);
               /* if (role.Rank != null && role.Rank.Count >= 0)
                {
                    this.RankButton.Visibility = Visibility.Visible;
                }*/
                role.Role.WinPercent = string.Format(" {0} / {1} / {2} ", role.Role.WinCount,
                    role.Role.MatchCount, (role.Role.WinCount / (float)role.Role.MatchCount).ToString("P"));
                this.RoleScrollViewer.Visibility = Visibility.Visible;
                this.RoleInfoControl.DataContext = role.Role;
            }
            else
            {
                this.RoleScrollViewer.Visibility = Visibility.Collapsed;
                GlobalIndicator.Instance.IsBusy = false;
                MessageBox.Show("没有搜索到该用户  ╮(╯﹏╰）╭");
            }
        }

        /// <summary>
        /// 获取角色战斗力
        /// </summary>
        /// <param name="role"></param>
        private void GetRoleEfficient(RoleInfo role)
        {
            var v = Config.HttpGetStringResult(RequestUrl.GetRoleEffectiveness(Str2UTF8(this.HeroReportTextBox.Text)))
             .Select(res =>
             {
                 var eff = res.Split('/')[4];
                 return eff == "5" ? "战5渣" : eff;
             }).ObserveOnDispatcher().Subscribe(
             s => role.Role.RoleEffficient = s,
                //异常处理
             ex => this.Dispatcher.BeginInvoke(() =>
             {
                 GlobalIndicator.Instance.IsBusy = false;
                 Config.Toast("网络错误,稍等一会儿.....", 800);
             }));
        }



        /// <summary>
        /// 键盘确认
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HeroReportTextBox_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                Search_Click(this.HeroReportTextBox, e);
                this.Focus();
            }
        }

        private string Str2UTF8(string res)
        {
            UTF8Encoding utf8Encoding = new UTF8Encoding();
            var a = utf8Encoding.GetBytes(res);
            return utf8Encoding.GetString(a, 0, a.Length);
        }

        #endregion

        #region  查看比赛列表
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            this.NavigationService.Navigate(new Uri(string.Format("/Pages/RoleListPage.xaml?{0}={1}", RoleListPage.NavigateKey, Str2UTF8(_roleInfo.Role.RoleName)), UriKind.Relative));
        }

        /// <summary>
        /// 从其他页面的搜索
        /// </summary>
        private void GetSearchRoleFromPages()
        {
            var v = NavigationHelper.NavigationExtGetStringValue(
                SearchReportHistoryPage.SearcHistoryKey);
            
            if (!string.IsNullOrWhiteSpace(v))
            {
             //   this.MainPivot.SelectedIndex = 3;
                this.HeroReportTextBox.Text = v;
                this.HeroTip.Visibility = Visibility.Collapsed;
                Search_Click(this.Search, new RoutedEventArgs());
            }
        }

        #endregion

        #endregion

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            GetSearchRoleFromPages();
            base.OnNavigatedTo(e);
        }

        #region Back键处理
        DateTime _lastTime = DateTime.MinValue;
        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {

            if (!this.NavigationService.CanGoBack && !e.Cancel && ApplicationBar.IsVisible)
            {
                //if (MessageBox.Show("您确认要退出 300英雄 资料站吗?", "温馨提示", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                //{
                //    base.OnBackKeyPress(e);
                //}
                //else
                //{
                //    e.Cancel = true;
                //}
                DateTime now = DateTime.Now;

                if ((now - _lastTime) >= new TimeSpan(0, 0, 0, 0, 2000))
                {
                    _lastTime = now;
                    // 提醒用户再按一次退出
                    ToastPrompt toast = new ToastPrompt();
                    toast.Dispose();
                    toast.MillisecondsUntilHidden = 1990;
                    toast.MaxHeight = 78;
                    toast.Message = "再按一次回退键退出程序 ( ^_^ )/~~";
                    toast.Show();
                    e.Cancel = true;
                }
                else
                {
                    base.OnBackKeyPress(e);
                }
            }
            base.OnBackKeyPress(e);

        }




        #endregion

        private void ApplicationBarMenuItem_OnClick(object sender, EventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/Pages/SearchReportHistoryPage.xaml", UriKind.Relative));
        }

        private void MainPivot_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {

            switch (MainPivot.SelectedIndex)
            {
                case 0:
                  
                    ApplicationBar = (Microsoft.Phone.Shell.ApplicationBar)Resources["ApplicationBar4"];
                    ApplicationBar.Mode = ApplicationBarMode.Minimized;
                    break;

                default:
                    ApplicationBar = (Microsoft.Phone.Shell.ApplicationBar)Resources["ApplicationBar4"];
                    ApplicationBar.Mode = ApplicationBarMode.Minimized;
                    break;
            }

        }
    }
     
}